package cn.juque.jdfsystem.task;

import cn.hutool.core.util.ArrayUtil;
import cn.juque.common.constants.StringConstants;
import cn.juque.common.utils.HttpClientUtil;
import cn.juque.common.utils.dto.GetDTO;
import cn.juque.jdfsystem.entity.FileInfo;
import cn.juque.jdfsystem.entity.RegisterInfo;
import cn.juque.jdfsystem.helper.RegisterInfoHelper;
import cn.juque.jdfsystem.mapper.FileInfoMapper;
import cn.juque.jdfsystem.service.IFileInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>FileAddTask</li>
 * </ul>
 * @date 2023-01-11 18:14:50
 **/
@Service("fileAddTask")
public class FileAddTask extends AbstractTask {

    private static final Integer ONE = 1;

    private static final Integer THREE = 3;

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private IFileInfoService fileInfoService;

    @Resource
    private RegisterInfoHelper registerInfoHelper;

    /**
     * 任务逻辑
     *
     * @param args 参数
     */
    @Override
    public void execute(String[] args) {
        if (ArrayUtil.isEmpty(args) || args.length <= ONE) {
            return;
        }
        String nodeName = args[0];
        String fileId;
        for (int i = 1; i < args.length; i++) {
            fileId = args[i];
            // 获取文件流
            byte[] bytes = this.downloadFile(nodeName, fileId);
            FileInfo fileInfo = this.fileInfoMapper.selectById(fileId);
            this.fileInfoService.saveFile(fileInfo, bytes);
        }
    }

    /**
     * 设置随机休眠等待最大时长 单位：秒
     *
     * @return 秒
     */
    @Override
    protected Integer initSleepTimes() {
        return THREE;
    }

    /**
     * 文件下载
     *
     * @param nodeName 节点名称
     * @param fileId   文件ID
     * @return 文件流
     */
    private byte[] downloadFile(String nodeName, String fileId) {
        RegisterInfo registerInfo = this.registerInfoHelper.getValidRegisterInfo(nodeName);
        String url = StringConstants.HTTP + registerInfo.getIp() + "/jdf/file/view/" + fileId + "?ignore=true";
        GetDTO getDTO = new GetDTO(url, null, null, null);
        return HttpClientUtil.download(getDTO);
    }
}
